import { getHistory, setHistory } from '@/utils/storage';

const initialState = {
  suggestion: [] as string[],
  histories: getHistory() || ([] as string[]),
  searchResults: [] as Article[],
};

// 定义search的action类型
export type SearchAction =
  | { type: 'search/saveSuggestion'; payload: string[] }
  | { type: 'search/clearSuggestion' }
  | { type: 'search/saveHistory'; payload: string }
  | { type: 'search/clearHistory' }
  | { type: 'search/saveResults'; payload: Article[] }
  | { type: 'search/clearResults' };

// 定义搜索结果类型
export type Article = {
  title: string;
  aut_id: number;
  pubdate: string;
  ch_id: number;
  cover: {
    type: 0 | 1 | 3;
    images: string[];
  };
  is_top: number;
  art_id: string;
  aut_name: string;
  comm_count: number;
  like_count: number;
  collect_count: number;
};

// 定义获取搜索结果参数类型
export type searchQuery = {
  page?: number;
  per_page?: number;
  q: string;
};
export default function searchReducer(
  state = initialState,
  action: SearchAction
): typeof initialState {
  switch (action.type) {
    // 修改suggestion数据
    case 'search/saveSuggestion':
      return {
        ...state,
        suggestion: action.payload.filter((item) => !!item),
      };

    // 清空redux中搜索建议
    case 'search/clearSuggestion':
      return {
        ...state,
        suggestion: [],
      };

    // 添加搜索历史记录
    case 'search/saveHistory':
      const histories = state.histories;
      const newHistory = Array.from(new Set([action.payload, ...histories]));
      if (newHistory.length > 10) newHistory.length = 10;
      setHistory(newHistory);
      return {
        ...state,
        // histories: [action.payload, ...state.histories],
        histories: newHistory,
      };

    // 清空全部搜索历史记录
    case 'search/clearHistory':
      return {
        ...state,
        histories: [],
      };

    // 保存搜索结果
    case 'search/saveResults':
      return {
        ...state,
        searchResults: action.payload,
      };

    // 清理搜索结果
    case 'search/clearResults':
      return {
        ...state,
        searchResults: [],
      };
    default:
      return state;
  }
}
